/**
 * Project Name:mauto-web
 * File Name:SessionUtil.java
 * Package Name:com.mingsoft.weixin.util.bean
 * Date:2016年10月31日下午1:22:16
 * Copyright (c) 2016, inf-technology Co., Ltd. All Rights Reserved.
 *
*/

package com.mingsoft.weixin.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mingsoft.util.JsonUtil;
import com.mingsoft.util.StringUtil;
import com.mingsoft.weixin.http.HttpClientConnectionManager;

/**
 * ClassName:SessionUtil <br/>
 * Function: 会话相关工具类. <br/>
 * Date: 2016年10月31日 下午1:22:16 <br/>
 * 
 * @author puyf
 * @version
 * @since JDK 1.7
 */
public class KfSessionUtils extends BaseUtils {
	/**
	 * @param appid
	 *            微信APPID
	 * @param secret
	 *            微信secret
	 */
	public KfSessionUtils(String appid, String secret) {
		super(appid, secret);
	}

	/**
	 * 
	 * getSession:获取客户会话状态. <br/>
	 *
	 * @author puyf
	 * @param openId
	 *            微信openId
	 * @return 客服帐号
	 * @since JDK 1.7
	 */
	public String getKfSession(String openId) throws Exception{
		String kfAccount = "";
		// 获取accessToken
		String accessToken = getAccessToken();
		if (!StringUtil.isBlank(accessToken)) {
				HTTPCLIENT = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(HTTPCLIENT);
				HttpGet get = HttpClientConnectionManager
						.getGetMethod(GET_KF_SESSION + accessToken + "&openid=" + openId);
				HttpResponse response = HTTPCLIENT.execute(get);
				String jsonStr = EntityUtils.toString(response.getEntity(), HttpClientConnectionManager.UTF8);

				Map object = JsonUtil.getMap4Json(jsonStr);
				logger.debug("获取客户会话状态:" + jsonStr);

				kfAccount = object.get(KF_ACCOUNT).toString();
		}
		return kfAccount;
	}

	/**
	 * 
	 * getKfList:获取客服列表. <br/>
	 *
	 * @author puyf
	 * @return
	 * @since JDK 1.7
	 */
	public List<Map<String, Object>> getKfList() throws Exception{
		List<Map<String, Object>> kfList = new ArrayList<Map<String, Object>>();
		// 获取accessToken
		String accessToken = getAccessToken();
		if (!StringUtil.isBlank(accessToken)) {
			JSONArray kfListJ = null;
			JSONArray kfOnlineListJ = null;
			// 查询所有客服列表
			HTTPCLIENT = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(HTTPCLIENT);
			HttpGet get = HttpClientConnectionManager.getGetMethod(GET_KF_LIST + accessToken);
			HttpResponse response = HTTPCLIENT.execute(get);
			String jsonStr = EntityUtils.toString(response.getEntity(), HttpClientConnectionManager.UTF8);
			logger.debug("获取客服列表:" + jsonStr);
			Map object = JsonUtil.getMap4Json(jsonStr);
			if (object.get(KF_LIST) != null) {
				kfListJ = (JSONArray) object.get(KF_LIST);
				// 查询在线客服列表
				get = HttpClientConnectionManager.getGetMethod(GET_ONLINE_KF_LIST + accessToken);
				response = HTTPCLIENT.execute(get);
				jsonStr = EntityUtils.toString(response.getEntity(), HttpClientConnectionManager.UTF8);
				logger.debug("获取在线客服列表:" + jsonStr);
				object = JsonUtil.getMap4Json(jsonStr);
				if (object.get(KF_ONLINE_LIST) != null) {
					kfOnlineListJ = (JSONArray) object.get(KF_ONLINE_LIST);
				}
			}
			if (kfListJ != null) {
				for (Object kfo : kfListJ) {
					JSONObject kfj = (JSONObject) kfo;
					Map<String, Object> kfm = new HashMap<String, Object>();
					// 客服账号
					kfm.put(KF_ACCOUNT, kfj.getString(KF_ACCOUNT));
					// 客服昵称
					kfm.put(KF_NICK, kfj.getString(KF_NICK));
					// 客服头像
					kfm.put(KF_HEADIMGURL, kfj.getString(KF_HEADIMGURL));
					// 客服状态(0:离线;1:在线空闲;2:在线忙碌)
					kfm.put(KF_STATUS, 0);
					if (kfOnlineListJ != null) {
						for (Object kfOnlineo : kfOnlineListJ) {
							JSONObject kfOnlinej = (JSONObject) kfOnlineo;
							if (kfOnlinej.getString(KF_ACCOUNT).equals(kfj.getString(KF_ACCOUNT))) {
								if (kfOnlinej.getInteger(ACCEPTED_CASE) == 0) {
									// 在线空闲
									kfm.put(KF_STATUS, 1);
								} else {
									// 在线忙碌
									kfm.put(KF_STATUS, 2);
								}
								break;
							}
						}
					}
					kfList.add(kfm);
				}
			}
		}
		return kfList;
	}

	/**
	 * 
	 * createSession:创建会话. <br/>
	 *
	 * @author puyf
	 * @param kfAccount
	 *            完整客服帐号
	 * @param openId
	 *            微信openId
	 * @return
	 * @since JDK 1.7
	 */
	public Boolean createKfSession(String kfAccount, String openId) throws Exception{
		Boolean result = false;
		// 获取accessToken
		String accessToken = getAccessToken();
		if (!StringUtil.isBlank(accessToken)) {
			String url = CREATE_KF_SESSION + accessToken;
			try {
				// 组装请求json
				String massageJson = XmlUtils.buildJsonCreateKfSession(kfAccount, openId);
				logger.debug("创建会话json：" + massageJson);
				String _jsonStr = this.sendPost(url, massageJson);
				logger.debug("创建会话返回值：" + _jsonStr);
				JSONObject object = JSON.parseObject(_jsonStr);
				result = object.getString(WEIXIN_JSON_ERR_STR).equals("ok");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	private String sendPost(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
}
